package com.dreamsail.core.service;

import com.dreamsail.core.constant.ErrorMessage;
import com.dreamsail.core.dao.UserInfoDao;
import com.dreamsail.core.entity.UserInfo;
import com.dreamsail.core.frame.ContentManager;
import com.dreamsail.core.model.system.BaseException;
import com.dreamsail.core.model.system.HeadMessage;
import com.dreamsail.core.model.system.PageInfo;
import com.dreamsail.core.model.system.PageReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerMapping;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserInfoDao userInfoDao;

    public UserInfo login(String account, String password) {
        UserInfo userInfo = userInfoDao.findByAccount(account);

        if(userInfo.getPassword().equals(password)){
            userInfo.setPassword("");
            return userInfo;
        }else{
            throw new BaseException(ErrorMessage.PASSWORD_ERROR);
        }
    }

    /**
     * 用户注册接口
     * @param account
     * @param password
     */
    public void sign(String account, String password) {
        UserInfo userInfo = userInfoDao.findByAccount(account);
        if(userInfo != null){
            throw new BaseException(ErrorMessage.HAS_USER);
        }
        UserInfo insertUser = new UserInfo();
        insertUser.setPassword(password);
        insertUser.setUserPhone(account);
        userInfoDao.insert(insertUser);
    }

    public void updatePassword(String password) {
        Long userId = ContentManager.getHeadMessage().getUserId();
        userInfoDao.updatePassword(userId,password);
    }

    public PageInfo<UserInfo> queryUserPage(PageReq<UserInfo> pageReq) {
        // TODO
        List<UserInfo> resultContent = userInfoDao.queryAllByLimit(pageReq.getQueryParam(),pageReq,pageReq.getQueryOrderList());
        long num = userInfoDao.count(pageReq.getQueryParam());

        return new PageInfo<>(resultContent,num,pageReq);
    }

    public UserInfo getInfo() {
        HeadMessage headMessage = ContentManager.getHeadMessage();
        UserInfo userInfo = userInfoDao.queryById(headMessage.getUserId());
        userInfo.setPassword("");
        return userInfo;
    }
}
